<template>
  <div>
    <div class="avue-upload">
      <div class="avue-upload avue-upload--list">
        <div class="el-upload el-upload--picture-img"
             @mouseenter.stop="changeActive"
             @mouseleave.stop="removeActive">
          <!-- 无图片时 && 添加编辑 -->
          <i v-if="!src && !disable"
             class="el-icon-plus avue-upload__icon"
             @click.stop="materialDialog = true"></i>
          <!-- 有图片时 || 查看 -->
          <template v-if="!!src || disable">
            <el-image :id="domElImageId"
                      class="avue-upload__avatar"
                      :src="src"
                      :preview-src-list="[ src ]" />
            <div :id="domElImageMenuId"
                 class="hidden-img">
              <i class="el-icon-zoom-in"
                 @click.stop="viewImg"></i>
              <i class="el-icon-delete"
                 v-if="!disable"
                 @click.stop="delImg"></i>
            </div>
          </template>
        </div>
      </div>
    </div>
    <upload-material @materialCallBack="materialCallBack"
                     materialType="image"
                     v-if="materialDialog" />
  </div>
</template>

<script>
export default {
  name: 'uploadForm',
  data () {
    return {
      src: undefined,
      disable: false,
      materialDialog: false,
    }
  },
  props: {
    id: {
      type: String,
      default: () => {
        return Math.ceil(Math.random() * 100) + '-';
      },
    },
    options: {
      type: Object,
      default: () => {
        return {};
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: undefined,
    },
  },
  computed: {
    domElImageId () {
      return "el-image-" + this.id;
    },
    domElImageMenuId () {
      return "el-image-menu" + this.id;
    }
  },
  mounted () {
    this.initValue()
  },
  methods: {
    materialCallBack (obj) {
      this.materialDialog = false
      if (obj && obj.length == 1) {
        this.src = obj[0].url
      }
      this.$emit('input', this.src)
    },
    initValue () {
      let timer = setTimeout(() => {
        if (!!this.value) {
          this.src = this.value
        }
        this.disable = this.disabled
        clearTimeout(timer)
      }, 0);
    },
    viewImg () {
      let ele = document.getElementById(this.domElImageId)
      if (ele) {
        ele.click()
      }
    },
    delImg () {
      if (this.disable) return
      this.src = undefined
      this.$emit('input', this.src)
    },
    changeActive () {
      let ele = document.getElementById(this.domElImageMenuId)
      if (ele) {
        ele.className = "el-upload-list__item-actions avue-upload__menu"
      }
    },
    removeActive () {
      let ele = document.getElementById(this.domElImageMenuId)
      if (ele) {
        ele.className = "hidden-img"
      }
    }
  }
}
</script>

<style scoped>
.hidden-img {
  display: none;
}
</style>